/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2013
 */

package com.lims.admin.service;

import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javacommon.base.*;

import cn.org.rapid_framework.page.*;

import com.lims.admin.model.*;
import com.lims.admin.dao.*;
import com.lims.admin.vo.query.*;

/**
 * @author badqiu email:badqiu(a)gmail.com
 * @version 1.0
 * @since 1.0
 */

@Service
@Transactional @SuppressWarnings("unchecked")
public class MenuManager extends BaseManager<Menu,java.lang.String>{

	private MenuDao menuDao;
	/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写*/
	public void setMenuDao(MenuDao dao) {
		this.menuDao = dao;
	}
	
	public EntityDao getEntityDao() {
		return this.menuDao;
	}
	
	@Transactional(readOnly=true)
	public Page findPage(MenuQuery query) {
		return menuDao.findPage(query);
	}
	
	@Transactional(readOnly=true)
	public List<Menu> findMenusByIds(String mids) {
		mids = mids.replace(",", "','");
		String hql = "from Menu as m where m.objid in('"+mids+"')";
		return menuDao.findByHQL(hql);
	}
	
	@Transactional(readOnly=true)
	public List<Menu> findMenusByRoleId(String rids) {
		String hql = "select r.menus from Role as r where r.objid='"+ rids+"'";
		return menuDao.findByHQL(hql);
	}
	/**
	 * 删除菜单前，先删除与角色的对应关系
	 * @param string
	 */
	public void removeAndcascadeById(String id) {
		Menu m = menuDao.getById(id);
		if(m== null) return ;
		List<Role> roles = m.getRoles();
		for (Iterator iterator = roles.iterator(); iterator.hasNext();) {
			Role role = (Role) iterator.next();
			role.getMenus().remove(m);
			menuDao.getHibernateTemplate().saveOrUpdate(role);
		}
		for(Iterator<Menu> iter = m.getMenus().iterator(); iter.hasNext();) {
			Menu tempM = iter.next();
			List<Role> rolesTemp = tempM.getRoles();
			for (Iterator iterator = rolesTemp.iterator(); iterator.hasNext();) {
				Role role = (Role) iterator.next();
				role.getMenus().remove(tempM);
				menuDao.getHibernateTemplate().saveOrUpdate(role);
			}
			menuDao.delete(tempM);
		}
		menuDao.delete(m);
	}
	/**
	 * 取出所有二级菜单 供分配菜单
	 * @param level
	 * @return
	 */
	public List findAllByLevel(Integer level) {
		return this.menuDao.findAllBy("menulevel", level);
	}
	
}
